package com.tanhua.recommend.job;

import com.tanhua.domain.mongo.Movement;
import com.tanhua.domain.mongo.RecommendMovement;
import org.apache.commons.lang3.RandomUtils;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Set;

@Component
public class RecommendMovementJob {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

//    @Scheduled(cron = "0 0/30 * * * ?") //每30分钟
    @Scheduled(cron = "0 * * * * ?") //每分钟
    public void redisToMongo(){
//        从redis中获取数据，放入到mongo recommend_movement

//        第一步：目前redis中有多少推荐圈子的用户  redis命令 keys QUANZI_PUBLISH_RECOMMEND_*
        Set<String> keys = redisTemplate.keys("QUANZI_PUBLISH_RECOMMEND_*");
//        keys有多少就代表有多少人
//        那么一个人一个人地处理
        for (String key : keys) {
            String userIdStr = key.replace("QUANZI_PUBLISH_RECOMMEND_","");
            Long userId = Long.parseLong(userIdStr);

//            把之前推荐给这个人的数据删除 delete from recommend_movement where userId=?
            mongoTemplate.remove(new Query(Criteria.where("userId").is(userId)),RecommendMovement.class);

//            key: QUANZI_PUBLISH_RECOMMEND_{USERID}
//            获取这个人对应的value值  "21,26,19,20,100099,28,10064,3,10020,20"
            String pidStr = redisTemplate.boundValueOps(key).get();
            String[] pidArray = pidStr.split(",");
            for (String pid : pidArray) {
                RecommendMovement recommendMovement = new RecommendMovement();
                recommendMovement.setUserId(userId);
//                根据pid查询movement，再获取movementId
                Movement movement = mongoTemplate.findOne(new Query(Criteria.where("pid").is(Long.parseLong(pid))), Movement.class);
                recommendMovement.setMovementId(movement.getId());
                recommendMovement.setId(new ObjectId());
                recommendMovement.setPid(Long.parseLong(pid));
                recommendMovement.setScore(RandomUtils.nextDouble(0,100));
                recommendMovement.setCreated(new Date().getTime());
                mongoTemplate.save(recommendMovement);

                System.out.println("执行了RecommendMovementJob的保存方法。。。。。。。。。。。");

            }
        }


    }


}
